#include "MHD_utils.h"

extern  mr_log_p MHD_log;
extern  mr_conf_p pconf;
int getMimeType(const char * filename,char **MimeType)
{
        char * p;
        struct mime_type_s * ps;
        static struct mime_type_s mytypes[] = {
        #include "mime_types.h"
        };

        if( (p = strrchr(filename, '.')) == NULL ) {
                *MimeType = mytypes[0].mime_type;
                return 1;
        }

        for( ps = mytypes; ps->ext; ps++ ) {
                if( !strcmp(p, ps->ext) ) {
                        *MimeType = ps->mime_type;
                        return 0;
                }
        }
        *MimeType = NULL;
        return -1;
}

/*
 * Parse a URL to find the next level node
 *
 *   value parsed is returned in root
 *   return:
  *      0       No more nodes found
 *    positive  new index into URL string
 *    negative  error
 */
int parse_url_node(const char *url, char *root, int start) {

	int i=start,j=0;

	while ((url[i]=='/') && (i < MAX_URL_LEN))
		i++;

	while (url[i] != '/' && url[i] != '\0' && i < MAX_URL_LEN)
		root[j++] = url[i++];

	root[j]='\0';

	if (i==MAX_URL_LEN)
		 return -1;

	if (j == 0)
		return 0;

	return i;
}
int response_write(struct MHD_Connection *connection,const char * mimeType, unsigned int status_code, char * format, ...){

	va_list args;
	struct MHD_Response *response;
	int ret, len;
	char * buffer;
	// MHD_HTTP_INTERNAL_SERVER_ERROR
	// MHD_HTTP_FORBIDDEN
	//  MHD_HTTP_NOT_FOUND
	//  MHD_HTTP_BAD_REQUEST
	//  MHD_HTTP_OK
	// DEBUG("\n");

	va_start(args,format);
	len = vsnprintf(0,0,format, args ); // _vscprintf doesn't count
        va_end(args);
        buffer = (char *)malloc( (len+1) * sizeof(char) );
	va_start(args,format);
	vsnprintf(buffer ,len+1,format, args);
        va_end(args);

	mr_logger_write(MHD_log,LL_TRACE,"buffer : %s \n",buffer);
        response =MHD_create_response_from_buffer (strlen (buffer),
                                        (void *) buffer,MHD_RESPMEM_MUST_COPY);
        ret = MHD_queue_response (connection,status_code , response);
        MHD_add_response_header (response, "Content-Type", mimeType);
        MHD_add_response_header (response, "Accept", "application/json, text/plain, */*");


        MHD_destroy_response (response);
        free(buffer);
        return ret;

}


inline int html_file_return (struct MHD_Connection *connection,
                const char *page,int status_code){

        int ret;
        struct MHD_Response *response;
        char * mime_type;
        int fd;
 	struct 	stat 	buf;
	char * dir;
	mr_conf_get(pconf,"www","docroot",&dir);
         char   path[strlen(dir) + strlen(page) + 1];
	strcpy(path, dir);	
	strcat(path, page);
	mr_logger_write(MHD_log,LL_TRACE,"path : %s \n",path);
	getMimeType(page,&mime_type);
      char *hack = strstr(page,"..");
              if(hack)
                               return  MHD_NO; 
	if(mime_type==NULL){
return 	response_write(connection,"text/html",MHD_HTTP_FORBIDDEN,"Forbidden File Extention");
	}
	if ((fd = open(path, O_RDONLY | O_CLOEXEC)) != -1) {

		if (!fstat(fd, &buf) &&((response = MHD_create_response_from_fd(buf.st_size, fd))))
		{
			MHD_add_response_header (response, "Content-Type", mime_type);
			ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
			MHD_destroy_response (response);
			return ret;
		}
		else 
		{
			close(fd);
			ret = response_write (connection, mime_type, MHD_HTTP_NOT_FOUND,
			"Error loading the file : %s ",page);
		}
	}
	else
		return MHD_NO;
	/*	ret = response_write (connection, mime_type, MHD_HTTP_NOT_FOUND,
				"not found  : %s ",page);*/

	return ret;

}


